using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Cart : MonoBehaviour
{
    public static Cart Instance;
    private List<Goods> goodsList = new List<Goods>();
    public Transform target;

    void Awake()
    {
        if (Instance == null)
        {
            Instance = this;
        }
    }

    void Start()
    {

    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        Goods goods = collision.gameObject.GetComponent<Goods>();
        if (goods != null)
        {
            if (goods.IsOnCart) return;
            StartCoroutine(CheckIfStopped(goods));
        }

        Debug.Log("进入了碰撞器");
    }

    private void OnTriggerExit2D(Collider2D collision)
    {

    }

    private IEnumerator CheckForMatchingGoods()
    {
        Dictionary<int, int> goodsCount = new Dictionary<int, int>();

        foreach (Goods goods in goodsList)
        {
            if (goodsCount.ContainsKey(goods.goodsId))
            {
                goodsCount[goods.goodsId]++;
            }
            else
            {
                goodsCount[goods.goodsId] = 1;
            }
        }

        List<Goods> goodsToRemove = new List<Goods>();

        foreach (KeyValuePair<int, int> entry in goodsCount)
        {
            if (entry.Value >= 3)
            {
                foreach (Goods goods in goodsList)
                {
                    if (goods.goodsId == entry.Key)
                    {
                        goodsToRemove.Add(goods);
                    }
                }
            }
        }

        // 创建一个协程列表来存储所有的 SetClear 操作
        List<Coroutine> clearCoroutines = new List<Coroutine>();

        // 同时启动所有 SetClear 操作
        foreach (Goods goods in goodsToRemove)
        {
            goodsList.Remove(goods);
            clearCoroutines.Add(StartCoroutine(goods.SetClearCoroutine()));
        }

        // 等待所有 SetClear 操作完成
        foreach (Coroutine coroutine in clearCoroutines)
        {
            yield return coroutine;
        }

        int allCount = GoodsManager.Instance.GetAllGoods().Count;
        Tools.Log("剩余：" + allCount + "个");

        if (allCount <= 0 && !Data.IsGameOver)
        {
            Data.IsGameOver = true;
            CountdownManager.Instance.Stop(); // 停止倒计时
            PanelManager.Instance.OpenPanel<PassPanel>();

            ClearAllGoods();
        }

    }

    private IEnumerator CheckIfStopped(Goods goods)
    {
        goods.IsOnCart = true;
        yield return new WaitForSeconds(0.5f);
        if (goods != null)
        {
            goodsList.Add(goods);
            goods.transform.SetParent(target);
            // goods.DisablePhysics();

            // 物体停止移动后执行的操作
            StartCoroutine(CheckForMatchingGoods());
        }
    }

    //清除所有物品
    public void ClearAllGoods()
    {

        foreach (Transform goods in target)
        {
            Destroy(goods.gameObject);
        }

        goodsList.Clear();

    }
}
